import {
  CancellationToken,
  Disposable,
  Webview,
  WebviewView,
  WebviewViewProvider,
  WebviewViewResolveContext,
  window,
} from 'vscode';
import { WebviewContainer } from './webview-container';

export class WebviewBase implements WebviewViewProvider, Disposable {
  protected _view!: WebviewView;

  protected readonly disposables: Disposable[] = [];

  constructor(protected container: WebviewContainer, protected id: string) {
    this.disposables.push(window.registerWebviewViewProvider(id, this));
  }

  dispose() {
    this.disposables.forEach(d => d.dispose());
  }

  async resolveWebviewView(
    webviewView: WebviewView,
    _context: WebviewViewResolveContext<unknown>,
    _token: CancellationToken,
  ): Promise<void> {
    this._view = webviewView;
    webviewView.webview.options = {
      enableCommandUris: true,
      enableScripts: true,
    };
    await this.refresh();
  }

  protected async refresh(force?: boolean): Promise<void> {
    if (this._view == null) return;

    const html = await this.getHtml(this._view.webview);
    if (force) {
      // 重置html以重新加载Web视图
      this._view.webview.html = '';
    }

    if (this._view.webview.html === html) {
      return;
    }

    this._view.webview.html = html;
  }

  protected async getHtml(_webview: Webview): Promise<string> {
    return `未实现`;
  }
}
